# Create your views here.
from .models import Xueyuan_zongbiao,Banji
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView, UpdateView, FormView, CreateView
from .forms import tzzy_banji_xueyuan_UpdateForm
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages
from KeHu.forms import KeHuzilaoForm
from jiaowu_xueyuan.forms import jiaowu_genjinlogForm, Xueyuan_Zilao_Update_Form
from jiaowu_xueyuan.models import xueyuan_jiaowu_genjinlog,Xueyuan_Zilao
from django.utils import timezone
from .forms import Xueyuan_zongbiao_form
from django.urls import reverse_lazy
from django.http import JsonResponse
from jiaowu_xueyuan.forms import Xueyuan_Add_Form
from KeHu.models import KeHu
from ChanPin.models import Dingdan
from django.core.paginator import Paginator
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import Group, User


#from esig_index import *



class Banji_List(LoginRequiredMixin, ListView):
    model = Banji
    template_name = 'banji/Banji.html'
    context_object_name = 'banji'

    def get_queryset(self):
        queryset = super().get_queryset()
        users=self.request.user
        if users.is_superuser:
            return queryset
        else:
            return queryset.filter(banji_leader=users)

class Banji_Detail(LoginRequiredMixin, DetailView):
    """班级详情"""
    model = Banji
    bigtitle="教务管理"
    smtitle="班级管理"
    context_object_name = 'banji_detail'
    paginate_by=10

    def get_template_names(self):
        """根据班级类型返回不同的模板"""
        obj = self.get_object()  # 获取当前班级对象
        print(f"self.object.banji_leibie>>>>>: {obj.banji_leibie}------{obj}")
        if obj.banji_leibie == "学历":
            return 'banji/banji_Detail_xueli.html'
        elif obj.banji_leibie == "特种作业":
            return 'banji/banji_Detail_tezhong.html'
        elif obj.banji_leibie == "职业资格证":
            return 'banji/banji_Detail_zhicheng.html'
        else:
            return 'banji/banji_Detail.html'


    def get_context_data(self, **kwargs):
        """添加额外的上下文数据"""
        from qxcrm_index.utils import search_xueyuan
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        context['smtitle'] = self.smtitle
        current_user = self.request.user
        xueyuan_set = self.object.xueyuan.all()  # 获取所有学员
        # 处理搜索
        search_term = self.request.GET.dict()  # 将 QueryDict 转换为普通字典
        xueyuan_set = search_xueyuan(xueyuan_set, search_term, current_user)
        print(f"self.object.xueyuan>>>>>: {xueyuan_set}")
        #

        paginator = Paginator(xueyuan_set, self.paginate_by)  # 创建分页器
        page_number = self.request.GET.get('page')  # 从请求中获取页码
        page_obj = paginator.get_page(page_number)  # 获取分页对象
        context['page_obj'] = page_obj  # 将分页对象添加到上下文
        context['search_query'] = search_term
        # 获取“销售老师”组
        sales_teacher_group, created = Group.objects.get_or_create(name='销售老师')

        # 获取属于“销售老师”组的用户
        zhuanhualaoshi = User.objects.filter(groups__name='销售老师')

        # 将查询结果添加到上下文中
        context['zhuanhualaoshi'] = zhuanhualaoshi
        return context



class Banji_xueyuan_Add(LoginRequiredMixin, FormView):
    """添加班级学员"""
    #model = Banji
    template_name = 'banji/banji_xueyuan_add.html'
    form_class = tzzy_banji_xueyuan_UpdateForm
    context_object_name =  'banji_xueyuan_add'
    def get_success_url(self):
        return f"/banji/{self.banji.id}/detail/"
    def dispatch(self, request, *args, **kwargs):
        self.banji = get_object_or_404(Banji, pk=kwargs['pk'])
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['banji_xueyuan_add'] = self.banji  # 将班级实例传递给模板
        context['tzzy_banji_xueyuan_update_form'] = tzzy_banji_xueyuan_UpdateForm(instance=self.banji)
        return context

    def form_valid(self, form):
        # 获取当前正在编辑的班级实例
        banji_instance = self.banji
        # 调用 save 方法，并传递班级实例作为参数
        form.save(banji_instance)
        # 重定向到成功页面
        return redirect(self.get_success_url())

class Xueyuan_Detail(LoginRequiredMixin, DetailView):
    """学员详情"""
    model = Xueyuan_zongbiao
    context_object_name = 'Xueyuan_Detail_index'
    template_name = 'Xueyuan_Detail_index.html'
    bigtitle="教务管理"
    smtitle="学员详情"

    # def get_template_names(self):
    #     """根据班级类型返回不同的模板"""
    #     # obj = self.get_object()  # 获取当前班级对象
    #     # if obj.banji_leibie == "学历":
    #     #     return 'banji/banji_Detail_xueli.html'
    #     # elif obj.banji_leibie == "特种作业":
    #     #     return 'banji/banji_Detail_tezhong.html'
    #     # elif obj.banji_leibie == "职业资格证":
    #     #     return 'banji/banji_Detail_zhicheng.html'
    #     # else:
    #     #     return 'banji/banji_Detail.html'
    #     return 'Xueyuan_Detail_index.html'

    def get_context_data(self, **kwargs):
        self.object = self.get_object()  # 确保这一行在调用 get_context_data 之前
        context = super().get_context_data(**kwargs)
        context['xueyuan_form'] = Xueyuan_zongbiao_form(instance=self.object)
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()  # 确保这一行在调用 get_context_data 之前
        print(f"Xueyuan_Detail视图 POST 数据 for {self.object}: {request}{request.GET}:{kwargs}")
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        context['Xueyuan_Zilao'] = Xueyuan_Zilao.objects.filter(xueyuan=self.object).first()

        context['jiaowu_genjinlogForm'] = jiaowu_genjinlogForm()  # 添加空表单到上下文
        context['Xueyuan_zongbiao_form'] = Xueyuan_zongbiao_form(instance=self.object)#载入学员信息表单
        jiaowu_genjinlog_list = xueyuan_jiaowu_genjinlog.objects.filter(kehu__kehu_id=self.object.kehu.id).all().order_by('-gengjin_time')
        context['jiaowu_genjinlog_list'] = jiaowu_genjinlog_list
        context['xueyuan_ziliao_form'] = KeHuzilaoForm()


        return self.render_to_response(context)  # 返回渲染后的响应

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form_key = request.POST.get('form_key')
        xueyuanid = request.POST.get('xueyuanid')
        print(f"Xueyuan_Detail视图 POST 数据 for {self.object}:-----{xueyuanid}--{form_key}----{request.POST}")
        forms = {
            'jiaowu_genjinlogForm': jiaowu_genjinlogForm(request.POST, instance=self.object if hasattr(self.object,'jiaowu_genjinlog') else None),
            'Xueyuan_zongbiao_form': Xueyuan_zongbiao_form(request.POST, request.FILES,instance=self.object if hasattr(self.object,'xueyuan_zongbiao') else None),
        }
        if form_key == "创建学员资料":
            try:
                Xueyuan_Zilao.objects.create(
                    xueyuan = self.object,
                    # csnyr = '2222-01-01',  # 正确的日期格式
                    # bysj = '2222-01-01',  # 正确的日期格式
                )
                messages.success(request, '创建成功')
                return redirect(f'/xueyuan/{self.object.pk}/detail/')
            except Exception as e:
                print(f"创建学员资料失败: {e}")
                messages.error(request, f'创建失败: {e}')
            return redirect(f'/xueyuan/{self.object.pk}/detail/')

        if form_key == "发送不分期协议":
            component_value = ["林晓彬", "445222198908154037"]
            getxtzl=Xueyuan_Zilao.objects.get(xueyuan=self.object)
            psn_value = [
                "林晓彬",
                "17688862308",
                "陈老师",
                # self.object.kehu.username,
                "18998415312"
                # ,getxtzl.tel
            ]
           # sqlstr=create_by_sign_template(component_value,psn_value)
          #  print("sqlstr:",sqlstr)

        if form_key in forms:
            form = forms[form_key]
            if form.is_valid():
                instance = form.save(commit=False)
                if form_key == 'jiaowu_genjinlogForm':
                    instance.addlog_user = request.user
                    instance.jiaowu_genjinlog_time = timezone.now()
                    # 假设 self.object 有 kehu 属性或关联
                    instance.kehu = self.object
                    instance.save()
                    messages.success(request, '添加成功')
                    return redirect(f'/xueyuan/{self.object.pk}/detail/#v-pills-jiaowugenjinlog')
                if form_key == 'Xueyuan_zongbiao_form':
                    # 这里可以添加额外的处理逻辑，如果有的话
                    instance.save()
                    messages.success(request, '修改成功')
                    return redirect(f'/xueyuan/{self.object.pk}/detail/')

            # 如果表单无效，则不保存，并显示错误信息（这里可以添加具体的错误处理）
            for key, value in form.errors.items():
                messages.error(request, f'{key}: {value}')
                print(f"{key}: {value}")
        else:
            messages.error(request, '无效的表单键，请检查表单输入是否有误。')
        # 如果没有匹配到有效的表单键或表单验证失败，则重定向回详情页面
        return redirect(f'/xueyuan/{self.object.pk}/detail/')

class Xueyuan_Update(LoginRequiredMixin, UpdateView):
    model = Xueyuan_zongbiao
    form_class = Xueyuan_zongbiao_form
    template_name = 'Xueyuan_Update.html'


    def get_success_url(self):
        success_url = reverse_lazy('Xueyuan_detail', kwargs={'pk': self.object.id})
        return success_url
    def form_valid(self, form):
        # 保存表单等操作...
        print(form.cleaned_data)
        self.object = form.save()
        # 返回一个JsonResponse给Ajax调用者
        # 返回 JSON 响应给 Ajax 调用者
        response_data = {
            'message': '表单提交成功！',
            'status': 'success',  # 自定义返回信息 status 为 success 告诉前端提交成功
            # 可以选择性地返回一些额外的数据，比如更新后的对象 ID
            # 'object_id': self.object.id,
        }
        return JsonResponse(response_data)  # 返回JSON响应而不是重定向
    def form_invalid(self,form):
        # 处理无效的表单提交情况...
        print(form.errors)
        response_data = {'errors': form.errors, 'status': 'failure'}  # 自定义返回信息 status -》failure 告诉前端提交失败
        for field, errors in form.errors.items():
            for error in errors:
                messages.error(self.request, error)
        return JsonResponse(response_data, status=400)
        # 返回重定向到表单页面（通常是当前页面），以便用户可以更正错误
        #return super().form_invalid(form)# 这将渲染表单并显示错误信息

class Xueyuan_list(LoginRequiredMixin, ListView):

    model = Xueyuan_zongbiao
    template_name = 'xueyuan_list.html'
    context_object_name = 'Xueyuan_list'
    paginate_by = 10
    bigtitle="教务管理"
    smtitle="正式学员列表"

    def get_queryset(self):
        from qxcrm_index.utils import search_xueyuan
        # 获取当前的用户
        current_user = self.request.user
        search_term = self.request.GET.dict()  # 将 QueryDict 转换为普通字典
        # 优化查询，使用 prefetch_related 来减少数据库查询次数
        queryset = Xueyuan_zongbiao.objects.prefetch_related('kehu__dingdan_set').order_by('xueyuan_jinbantime')
        queryset = search_xueyuan(queryset, search_term, current_user)
        print(f"queryset-----------{queryset}")
        # 判断当前用户是否为超级用户
        if current_user.is_superuser:
            # 如果是超级用户，返回过滤后的查询集（超级用户可以查看所有记录）
            return queryset
        else:
            # 如果不是超级用户，只返回过滤后且 admin_user 字段等于当前用户的记录（非超级用户只能查看自己的记录）
            #return queryset.filter(chengjiao_laoshi=current_user)
            print(queryset.filter(chengjiao_laoshi=current_user))
            return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        context['smtitle'] = self.smtitle
        # 分页
        page = context['page_obj']
        context['has_previous'] = page.has_previous()
        context['has_next'] = page.has_next()
        context['previous_page_number'] = page.previous_page_number() if page.has_previous() else None
        context['next_page_number'] = page.next_page_number() if page.has_next() else None

        xueyuan_to_dingdan = {}
        for xueyuan in context['Xueyuan_list']:
            # 由于使用了 prefetch_related，我们可以直接访问 kehu.dingdan_set.all()
            xueyuan_dingdan = xueyuan.kehu.dingdan_set.all()
            xueyuan_to_dingdan[xueyuan] = xueyuan_dingdan
        context['xueyuan_to_dingdan'] = xueyuan_to_dingdan
        return context

class Xueyuan_ziliao_UpdateView(LoginRequiredMixin,UpdateView):
    """修改正式学员资料"""
    model = Xueyuan_Zilao
    form_class = Xueyuan_Zilao_Update_Form
    template_name = 'Xueyuan_ziliao_Update.html'
    context_object_name = 'Xueyuan_Zilao'
    paginate_by = 10

    def get_success_url(self):
        return f"/xueyuan/{self.object.pk}/detail/"

class Xueyuan_add(LoginRequiredMixin,CreateView):
    model = Xueyuan_zongbiao
    form_class =Xueyuan_Add_Form
    template_name = 'Xueyuan_add.html'

    def get_success_url(self):
        # 使用 reverse_lazy 替代硬编码的 URL
        return reverse_lazy('xueyuan_detail', kwargs={'pk': self.object.pk})

    def form_valid(self, form):

        for kehu in self.object:
            KeHu(
                    username=kehu.username,
                    tel=kehu.tel,
                    wechat=kehu.wechat,
                    qq=kehu.qq,
                    tg_qudao=kehu.tg_qudao,
            )
            return super().form_valid(form)



















